<?php

declare(strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;
use app\common\controller\Config;

class Deal extends Base
{
    protected $name = 'deal';

    protected $type = [
        'repeal_time' => 'timestamp',
    ];

    public function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')->field('id,code,nickname,mobile');
    }

    public function getStatusTextAttr($value, $data)
    {
        return self::getDealStatus($data['status']);
    }

    public static function getDealStatus($value, $type = 1)
    {
        $status = [1 => '交易中', 2 => '已完成', 3 => '已撤销'];
        return $type == 1 ? $status[$value] : $status;
    }
    public function getTypeTextAttr($value, $data)
    {
        return self::getDealType($data['type']);
    }

    public static function getDealType($value, $type = 1)
    {
        $status = [1 => '买单', 2 => '卖单'];
        return $type == 1 ? $status[$value] : $status;
    }
    
    public function getEndNumAttr($value, $data)
    {
        $sum = DealOrder::where(['deal_id' => $data['id']])->sum('num');
        return $data['num'] - $sum > 0 ? $data['num'] - $sum : 0;
    }
    public function getEndMoneyAttr($value, $data)
    {
        $sum = DealOrder::where(['deal_id' => $data['id']])->sum('money');
        return $data['money'] - $sum > 0 ? $data['money'] - $sum : 0;
    }
    /**
     * 发布交易
     */
    public static function add($param, $user)
    {
        if(empty($param['id'])){
            $open = get_trade_status(1);
            if($open['code'] == 0){
                return ['code' =>-1,'msg'=>$open['msg']];
            }
        }
        parent::startTrans();
        try {
            $sys = Config::lists();
            $num_money = floatval($param['num']);
            $money = round($param['price'] * $num_money, 2);
            if (md5($param['pay_password']) != $user['pay_password']) {
                return ['code' => -1, 'msg' => '支付密码错误'];
            }
            if (empty($param['id'])) {
                if((!$user['bank_open'] || !$user['bank_number'] || !$user['bank_name'] || !$user['bank_account_name']) && (!$user['wechat_name'] || !$user['wechat_image']) && (!$user['alipay_name'] || !$user['alipay_image'])){
                    return ['code' => -1, 'msg' => '请完善收款方式！'];
                }
                $ratio_money = round($num_money * $sys['buy_ratio'] * $param['price'], 2);
                if ($user->assets->currency < $ratio_money) {
                    return ['code' => -1, 'msg' => '余额不足'];
                }
                // $my_money = DealOrder::where(['buy_uid' => $user->id])->where('status','<>',4)->sum('num')+$num_money;
                // if($param['type']==1){
                //     $lock_money = round($user->assets->lock *$sys['lock_bs'], 2);
                //     if($my_money>$lock_money){
                //         return ['code' => -1, 'msg' => $lock_money>0?'不得超过锁仓金额：'.$lock_money:'无锁仓金额'];
                //     }
                // }
                if ($user->assets->sold < $num_money && $param['type'] == 2) {
                    return ['code' => -1, 'msg' => '可出售金额不足！'];
                }
                $create['uid'] = $user->id;
                $create['price'] = $param['price'];
                $create['num'] = $num_money;
                $create['type'] = $param['type'];
                $create['buy_ratio'] = $ratio_money;
                $create['money'] = $money;
                parent::create($create);
                Target::Account()->basics($user->id, 'currency', $ratio_money, '发布'.($param['type'] == 2?"卖单":"买单").'扣除手续费', '-')->createNormal();
                if ($param['type'] == 2) {
                    Target::Account()->basics($user->id, 'sold', $num_money, '发布卖单扣除费用', '-')->createNormal();
                    Target::Account()->basics($user->id, 'freeze', $num_money, '发布卖单冻结账户', '+')->createNormal();
                }
                $msg = '发布交易成功';
                parent::commit();
                return ['code' => 1, 'msg' => $msg];
            } else {
                $info = parent::find($param['id']);
                $ratio_money = round($num_money * $sys['deal_money']*$param['price'], 2);
                // $my_money = DealOrder::where(['buy_uid' => $user->id])->where('status','<>',4)->sum('num')+$num_money;
                // if($param['type']==2){
                //     $lock_money = round($user->assets->lock *$sys['lock_bs'], 2);
                //     if($my_money>$lock_money){
                //         return ['code' => -1, 'msg' => $lock_money>0?'不得超过锁仓金额：'.$lock_money:'无锁仓金额'];
                //     }
                // }
                if ($user->assets->currency < $ratio_money) {
                    return ['code' => -1, 'msg' => '余额不足'];
                }
                if (empty($info)) {
                    return ['code' => -1, 'msg' => '交易不存在'];
                }
                if ($info->uid == $user->id) {
                    return ['code' => -1, 'msg' => '不能购买自己的交易'];
                }
                $num = DealOrder::where(['deal_id' => $info->id])->sum('num');
                if ($num_money > ($info->num - $num)) {
                    return ['code' => -1, 'msg' => '交易已满额'];
                }

                if ($user->assets->sold < $num_money && $info['type'] == 1) {
                    return ['code' => -1, 'msg' => '可出售金额不足！'];
                }
                $create['uid'] = $info['type'] == 2 ? $info['uid'] : $user->id;
                $create['buy_uid'] = $info['type'] == 2 ? $user->id : $info['uid'];
                $create['deal_id'] = $info->id;
                $create['price'] = $param['price'];
                $create['num'] = $num_money;
                $create['type'] = $info['type'] == 1 ? 2 : 1;
                $create['buy_ratio'] = $ratio_money;
                $create['money'] = $money;
                // print_r($create);die;
                DealOrder::create($create);
                $title = $info['type'] == 2 ? '买入' : '卖出';
                Target::Account()->basics($user->id, 'currency', $ratio_money, $title . '扣除手续费', '-')->createNormal();
                if ($info['type'] == 1) {
                    Target::Account()->basics($user->id, 'sold', $num_money, $title.'扣除费用', '-')->createNormal();
                    Target::Account()->basics($user->id, 'freeze', $num_money, $title.'冻结账户', '+')->createNormal();
                }
                $msg = $title . '成功';
                parent::commit();
                return ['code' => 1, 'msg' => $msg,'url'=> url('user/deal')->build() . '?type='.$param['type'],'type'=>$param['type'],'open'=>1];
            }
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 撤销交易
     */
    public static function repeal($param, $user)
    {
        parent::startTrans();
        try {
            $info = parent::find($param['id']);
            if (empty($info)) {
                return ['code' => -1, 'msg' => '交易不存在'];
            }
            if ($info->uid != $user->id) {
                return ['code' => -1, 'msg' => '非本人交易不能撤销'];
            }
            if ($info->status != 1) {
                return ['code' => -1, 'msg' => '撤销状态错误'];
            }
            $info->status = 3;
            $info->repeal_time = time();
            $info->save();
            parent::commit();
            $buy_ratio= DealOrder::where(['deal_id' => $info->id])->sum('buy_ratio');
            $money= DealOrder::where(['deal_id' => $info->id])->sum('num');
            Target::Account()->basics($user->id, 'currency', round($info->buy_ratio - $buy_ratio,2), '交易撤回手续费返还', '+')->createNormal();
            if ($info['type'] == 2) {
                Target::Account()->basics($user->id, 'sold', round($info->num-$money,2), '交易撤回可出售返还', '+')->createNormal();
                Target::Account()->basics($user->id, 'freeze',round($info->num-$money,2), '交易撤回冻结账户返还', '-')->createNormal();
            }
            return ['code' => 1, 'msg' => '撤销成功'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
